import { Toast } from "@/utils/toast";
import { delayTask } from "@/utils/timer";

export const requestPayment = (
  options: UniApp.RequestPaymentOptions,
  success: () => void,
  cancel?: () => void,
  fail?: (e: Error) => void
) => {
  uni.requestPayment({
    ...options,
    success: () => {
      // 延迟 1s 等待支付结果
      Toast.showLoading();
      delayTask(3000, () => {
        Toast.hideLoading();
        success();
      });
    },
    fail: error => {
      console.error(error);
      if (error.errMsg.includes("cancel")) {
        Toast.show("支付已经取消");
        cancel?.();
      } else {
        fail?.(new Error(error.errMsg));
        Toast.show(error.errMsg);
      }
    },
  });
};
